Nullish coalescing operator(??) in Javascript


Published on: February 02, 2021 By T.Andrew Rayan

In this article, we shall see what is nullish coalescing operator? and how to use it to handle a variable that is null or undefined.

This operator is represented with the two question marks ??.

The expression, a??b; will return the value of a if it is defined and not null, else it will return the value of b.

Example

Output

10

Here the variable a is declared but it's not defined with any value. So it will return the value of b.

If we rewrite the above example as below,

Output

10

Since the value of a is null it will return the value of b.

So the operator ?? is shortcut representation of the following

(a!==undefined && a!==null)? a:b;

The main use of this nullish coalescing operator ?? is to provide some default value if the value of the variable is undefined.

Example

This will return USD since the currency is not defined with any value.

We can also check multiple condition like below,

This will return the value Default.


Most Read